/** <a href="http://www.cpupk.com/decompiler">Eclipse Class Decompiler</a> plugin, Copyright (c) 2017 Chen Chao. **/
package com.asiainfo.utils.sql.sqlbuilder.select;

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

abstract class Condition {
	private final Context context;

	Condition(Context context) {
		this.context = context;
	}

	void add(Object condition) {
		this.context.append(new StringBuilder().append(getPrefix()).append(" ").append(condition).toString());
	}

	void add(Object condition, Object parameter) {
		if (parameter != null)
			add(condition, new Object[]{parameter});
	}

	void add(String condition, String parameter) {
		if (StringUtils.isNotBlank(parameter))
			add(condition, new Object[]{parameter});
	}

	void add(Object condition, Object[] parameters) {
		if (ArrayUtils.isNotEmpty(parameters)) {
			this.context.addParameters(parameters);
			add(condition);
		}
	}

	void between(String columnName, Object start, Object end) {
		if (start == null) {
			if (end == null) {
				return;
			}
			add(new StringBuilder().append(columnName).append(" <= ?").toString(), end);
		} else if (end == null) {
			add(new StringBuilder().append(columnName).append(" >= ?").toString(), start);
		} else {
			add(new StringBuilder().append(columnName).append(" BETWEEN ? AND ?").toString(), new Object[]{start, end});
		}
	}

	void in(String columnName, Object[] objects) {
		if (ArrayUtils.isNotEmpty(objects)) {
			StringBuilder vals = new StringBuilder();
			List ps = new ArrayList();
			for (Object object : objects) {
				vals.append(" , ? ");
				ps.add(object);
			}
			this.context.addParameters(new Object[]{ps});
			add(new StringBuilder().append(columnName).append(" in (").append(vals.toString().substring(3)).append(")")
					.toString());
		}
	}

	void in(Object columnName, Object[] parameters) {
		StringBuilder vals = new StringBuilder();
		for (Object object : parameters) {
			vals.append(" , ? ");
		}
		this.context.addParameters(parameters);
		add(new StringBuilder().append(columnName).append(" in (").append(vals.toString().substring(3)).append(")")
				.toString());
	}

	protected abstract String getPrefix();
}